package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_KEY;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result getList() {
//        List<ShopType> typeList = typeService
//                .query().orderByAsc("sort").list();

//        先查询redis中是否存在数据
        String json = stringRedisTemplate.opsForValue().get(CACHE_SHOP_TYPE + "*");

        if (StrUtil.isNotBlank(json)){
            List<ShopType> list = JSONUtil.toList(json, ShopType.class);
            return Result.ok(list);
        }

        //如果不存在则查询数据库
        List<ShopType> typeList = query().orderByAsc("sort").list();

        //如果数据库查询为空，则直接返回
        if (typeList == null ){
            return Result.fail("数据库中没有数据");
        }
        String s = JSONUtil.toJsonStr(typeList);
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_TYPE,s);

        return Result.ok(typeList) ;

    }
}
